package com.glc.hms.core.compress.algorithm;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * 数据压缩解压缩抽象方法
 *
 * @author Lin
 * @time 2019-12-04 22:06
 */
@Slf4j
public abstract class AbstractCompressAlgorithm implements CompressAlgorithm {

    protected static final int BUFFER_SIZE = 2048;

    protected abstract OutputStream createOutputStream(OutputStream output) throws IOException;

    protected abstract InputStream createInputStream(InputStream input) throws IOException;

    @Override
    public byte[] compress(byte[] data) {
        if (data == null) {
            return new byte[0];
        }

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             OutputStream cs = createOutputStream(baos)) {
            cs.write(data);
            return baos.toByteArray();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }

        return new byte[0];
    }

    @Override
    public byte[] decompress(byte[] data) {
        if (data == null || data.length == 0) {
            return null;
        }

        int len;
        byte[] buffer = new byte[BUFFER_SIZE];
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             InputStream is = createInputStream(new ByteArrayInputStream(data))) {
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            return baos.toByteArray();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }

        return null;
    }
}
